<?php

namespace App\Service\User;

use App\DataStore\RedisGeneral;
use App\Model\Divistion\DivisionUserModel;
use App\Model\User\UserModel;
use App\Repository\Contro\DivisionContro;
use App\Repository\Contro\DivisionUserContro;
use App\Repository\Contro\UserContro;
use App\Service\ServiceGeneral;
use App\Service\System\EncryptionService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Ramsey\Uuid\Uuid;

class UserService extends ServiceGeneral
{


    #[Inject]
    public UserContro $userContro;
    #[Inject]
    public DivisionContro $divisionContro;
    #[Inject]
    public DivisionUserContro $divisionUserContro;
    #[Inject]
    public DivisionUserModel $divisionUserModel;
    #[Inject]
    public UserModel $userModel;

    #[Inject]
    public EncryptionService $encryptionService;

    public function getUserPuKey(string $account){
        $userInfo =  $this->userContro->getUserInfoByAccount($account,['pu_key']);
        if(empty($userInfo)){
            apiError("当前账号不存在");
        }
        return $userInfo['pu_key'];
    }

    public function getUserInfoByAccountPassowrd($data){
        $account = $data['user_account'];
        $password = $data['password'];
        $key = $data['key'];
        // 解码数据
        $userInfo = $this->userContro->getUserInfoByAccount($account,[
            'organ_id',
            'user_name',
            'user_account',
            'user_password',
            'user_phone',
            'user_email',
            'user_type',
            'pv_key'
        ]);

        // 校验密码
        if(empty($userInfo)){
            apiError("账号或密码错误");
        }
        // 解码aesKey
        $aesKey = $this->encryptionService->rsaDecrypt($key,$userInfo['pv_key']);
        if(empty($aesKey)){
            apiError("签名验证错误");
        }
        // 解密密码
        $password = $this->encryptionService->aesEcbDecrypt($password,$aesKey);
        if (password_verify($password, $userInfo['user_password'])) {
            apiError("账号或密码错误");
        }
        $token = md5(Uuid::uuid4()->toString());
        unset($userInfo['pv_key']);
        RedisGeneral::getInc()->setUserKey($token,$userInfo);

        return [
            'token' => $token,
            'user_name' => $userInfo['user_name']
        ];
    }

    public function addUser(array $data) : array{
        $rsaKes = getPuPvKey();
        $exists = $this->userContro->userExists($data);
        if($exists){
            apiError("当前用户已经存在");
        }

        $division = $this->divisionContro->getDivision($data['division_id'],['id']);
        if(!$division){
            apiError("组织结构错误");
        }

        try {
            Db::connection('organ')->beginTransaction();
            $user = $this->userContro->addUser([
                'organ_id' => getOrganIdByOrganCode(),
                'user_name' => $data['user_name'],
                'user_account' => $data['user_account'],
                'user_password' => password_hash($data['user_password'], PASSWORD_DEFAULT),
                'user_phone' => $data['user_phone'],
                'user_email' => $data['user_email'],
                'user_type' => $data['user_type'],
                'pv_key' => $rsaKes['pu_key'],
                'pu_key' => $rsaKes['pv_key']
            ]);

            $this->divisionUserContro->addDivisionUser([
                'division_id' => $data['division_id'],
                'user_id' => $user->id
            ]);
            Db::connection('organ')->commit();
        }catch (\Exception $exception){
            Db::connection('organ')->rollBack();
            apiError("新增用户异常");
        }
        return [
            'user_id' => $user->id
        ];
    }

    public function getUserListByDivision(int $divisionId,array $filters  = []){
        $users = $this->divisionUserModel->select(['user_id'])->where('division_id',$divisionId)->get()->toArray();
        if(empty($users)){
            return [];
        }
        $users = array_column($users,'user_id');

        $page = $this->request->post('page_size',1);
        $users = $this->userModel
            ->select([
            'user_name',
            'user_account',
            'user_type',
        ])->whereIn('id',$users)
        ->paginate($page);
        return $users;
    }
}